import sys
import os

from plugins.UUCrawl.utils import crawl_goods

sys.path.append(os.path.dirname(__file__))
from mysql_assistant import MySQLAssistant

class Quant:
    valid_map = {
        'CSGO_Tool_Sticker': ['金色', '全息'],
        'CSGO_Type_Knife': ['崭新出厂', '略有磨损', '无涂装'],
        'Type_Hands': ['崭新出厂', '略有磨损', '久经沙场'],
        'Type_CustomPlayer': [''],
        'default': ['崭新出厂', '略有磨损']
    }

    mysql = MySQLAssistant(config={
        'host': 'localhost',
        'user': 'Bot',
        'password': 'Yx030411',
        'database': 'QQBot'
    })

    create_table_sql = """
    CREATE TABLE IF NOT EXISTS UUCrawlQuant (
        id INT AUTO_INCREMENT PRIMARY KEY,
        template_id INT(4) NOT NULL,
        type VARCHAR(32) NOT NULL,
        name VARCHAR(32),
        min_price FLOAT(16,2),
        on_sale_count INT(8),
        on_lease_count INT(8),
        lease_unit_price FLOAT(16,2),
        long_lease_unit_price FLOAT(16,2),
        lease_deposit FLOAT(16,2),
        date DATETIME,
        UNIQUE KEY (id),
        INDEX uukey (template_id)
    )
    """

    def init(self):
        self.mysql.connect()
        self.mysql.create_table_if_not_exists("UUCrawlQuant", create_table_sql=self.create_table_sql)

        template_id = 0
        cur = 100000
        while(template_id < 120000):
            records = self.mysql.execute_query("""
                SELECT * FROM UUCrawlQuant ORDER BY template_id DESC LIMIT 1
            """)
            if len(records) != 0:
                template_id = max(int(records[0]['template_id']), cur)

            try:
                res = crawl_goods(list(range(int(template_id), int(template_id) + 51)), 0.2)
            except Exception as e:
                print(e)
            cur = int(template_id) + 51
            print(cur)
            insert2mysql = []
            for item in res:
                if item.type in self.valid_map and item.exterior not in self.valid_map[item.type]:
                    continue
                if item.type not in self.valid_map and item.exterior not in self.valid_map['default']:
                    continue
                insert2mysql.append({
                    'template_id': item.template_id,
                    'name': item.name,
                    'type': item.type,
                    'min_price': item.min_price,
                    'on_sale_count': item.on_sale_count,
                    'on_lease_count': item.on_lease_count,
                    'lease_unit_price': item.lease_unit_price,
                    'long_lease_unit_price': item.long_lease_unit_price,
                    'lease_deposit': item.lease_deposit,
                    'date': item.time
                })
            self.mysql.insert_data("UUCrawlQuant", insert2mysql)
